//
//  MyViewController.m
//  JZMCFM
//
//  Created by Mc on 15/11/7.
//  Copyright (c) 2015年 陈卓. All rights reserved.
//

#import "MyViewController.h"
#import "LoginViewController.h"
#import <AVFoundation/AVFoundation.h>

#import "MapViewController.h"
@interface MyViewController ()<UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate,UIAlertViewDelegate,AVCaptureMetadataOutputObjectsDelegate>

@property (strong, nonatomic) IBOutlet UITableView *mainTableView;
@property(nonatomic,strong)NSArray *dataArray;
@property(nonatomic,strong)AVCaptureSession *capture;
@property(nonatomic,strong)AVCaptureVideoPreviewLayer *previewLayer;

@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%@",[NSBundle mainBundle].bundleIdentifier);
   
    
    self.dataArray = [NSArray arrayWithObjects:@"更换头像",@"夜间模式",@"清除缓存",@"扫一扫",@"当前位置",@"意见反馈",@"关于", nil];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"my" forIndexPath:indexPath];
    if (indexPath.row == 2) {
        float num = [[SDImageCache sharedImageCache] getSize] / 1024.0 / 1024.0;
        NSString *str = [NSString stringWithFormat:@"%@(%.2f)",@"清除缓存",num];
        cell.textLabel.text = str;
    }else{
        cell.textLabel.text = self.dataArray[indexPath.row];
    }
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kscreenwidth, 200)];
    self.imageView.image = [UIImage imageNamed:@"touxiang.jpg"];
    UIBlurEffect *beffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    UIVisualEffectView *view1 = [[UIVisualEffectView alloc]initWithEffect:beffect];
    self.imageView.userInteractionEnabled = YES;
    view1.frame = self.imageView.bounds;
    [self.imageView addSubview:view1];
    
    self.imageV = [[UIImageView alloc] initWithFrame:CGRectMake(kscreenwidth / 2 - 50, 30, 100, 100)];
    self.imageV.image = [UIImage imageNamed:@"touxiang.jpg"];
    [self.imageView addSubview:self.imageV];
    self.imageV.layer.cornerRadius = 50;
    self.imageV.clipsToBounds = YES;
    
    if ([LoginMangager sharedInstance].isLogin == YES) {
        
    }else{
        self.loginButton = [UIButton buttonWithType:UIButtonTypeSystem];
        [self.loginButton addTarget:self action:@selector(loginButtonAvtion:) forControlEvents:UIControlEventTouchUpInside];
        self.loginButton.frame = CGRectMake(kscreenwidth / 2 - 30, CGRectGetMaxY(self.imageV.frame), 60, 60);
        [self.loginButton setTitle:@"登录" forState:UIControlStateNormal];
        [self.loginButton setTintColor:[UIColor whiteColor]];
        [self.imageView addSubview:self.loginButton];
    }
    
    return self.imageView;
}

- (void)loginButtonAvtion:(UIButton *)sender
{
    LoginViewController *vc = [[LoginViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 200;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *message = nil;
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        if ([LoginMangager sharedInstance].isLogin == YES) {
            [self touxiang];
        }else{
            [self loginButtonAvtion:nil];
        }
    }else if (indexPath.row == 1){
        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"night"] == NO) {
            message = @"要开启夜间模式吗?";
        }else{
            message = @"要关闭夜间模式吗?";
        }
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alert show];
    }else if (indexPath.row == 2){
        [[SDImageCache sharedImageCache] cleanDisk];
        
        [self.mainTableView reloadData];
        [self performSelectorOnMainThread:@selector(cleanCaches) withObject:nil waitUntilDone:YES];
    }else if (indexPath.row == 3){
        [self saoyisao];
    }else if (indexPath.row == 4){
        MapViewController *vc = [[MapViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.row == 5){
        
    }
    
}

#pragma mark - 扫一扫delegate
- (void)saoyisao
{
    // 1. 实例化拍摄设备 ,拿到摄像头
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // 2. 设置输入设备,把摄像头设置为输入源
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
    // 3. 设置元数据输出
    // 3.1 实例化拍摄元数据输出
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    // 3.3 设置输出数据代理
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // 4. 添加拍摄会话
    // 4.1 实例化拍摄会话
    AVCaptureSession *session = [[AVCaptureSession alloc] init];
    // 4.2 添加会话输入
    [session addInput:input];
    // 4.3 添加会话输出
    [session addOutput:output];
    // 4.3 设置输出数据类型，需要将元数据输出添加到会话后，才能指定元数据类型，否则会报错
    [output setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode]];
    
    self.capture = session;
    
    // 5. 视频预览图层
    // 5.1 实例化预览图层, 传递_session是为了告诉图层将来显示什么内容
    AVCaptureVideoPreviewLayer *preview = [AVCaptureVideoPreviewLayer layerWithSession:_capture];
    
    preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    preview.frame = self.view.bounds;
    // 5.2 将图层插入当前视图
    [self.view.layer insertSublayer:preview atIndex:100];
    
    self.previewLayer = preview;
    
    // 6. 启动会话
    [_capture startRunning];
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    // 会频繁的扫描，调用代理方法
    // 1. 如果扫描完成，停止会话
    [self.capture stopRunning];
    // 2. 删除预览图层
    [self.previewLayer removeFromSuperlayer];
    
    NSLog(@"%@", metadataObjects);
    // 3. 设置界面显示扫描结果
    
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *obj = metadataObjects[0];
        // 提示：如果需要对url或者名片等信息进行扫描，可以在此进行扩展！
        //        _label.text = obj.stringValue;
        NSLog(@"%@", obj.stringValue);
    }
}


- (void)cleanCaches
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"清除缓存成功" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [alert show];
    [self performSelector:@selector(removeAllert:) withObject:alert afterDelay:0.3];
}

- (void)removeAllert:(UIAlertView *)sender
{
    [sender dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"night"] == NO) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"night"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"night" object:@1];
        }else{
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"night"];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"night" object:@0];
        }
    }
}

- (void)touxiang
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        [self.navigationController presentViewController:imagePicker animated:YES completion:nil];
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
            imagePicker.delegate = self;
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self.navigationController presentViewController:imagePicker animated:YES completion:nil];
        }else{
            NSLog(@"没有相机");
        }
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self.navigationController presentViewController:alert animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
    }
    
    self.imageView.image = image;
    self.imageV.image = image;
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
